package com.example.bpmn.delegate;

import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.ArrayList;

@Slf4j
@Component
@RequiredArgsConstructor
public class WarehouseProcessDelegate implements JavaDelegate {

    @Override
    public void execute(DelegateExecution execution) throws Exception {
        String taskDefinitionKey = execution.getCurrentActivityId();
        switch (taskDefinitionKey) {
            case "Task_InventoryCheck":
                checkInventory(execution);
                break;
            case "Task_LocationAllocation":
                allocateLocation(execution);
                break;
            case "Task_PickTaskGeneration":
                generatePickTask(execution);
                break;
            case "Task_OutboundGeneration":
                generateOutbound(execution);
                break;
            case "Task_PurchaseInbound":
                handlePurchaseInbound(execution);
                break;
            case "Task_InboundSorting":
                handleInboundSorting(execution);
                break;
            case "Task_HotDelivery":
                handleHotDelivery(execution);
                break;
            case "Task_QualityCheck":
                handleQualityCheck(execution);
                break;
            default:
                log.warn("未知的任务类型: {}", taskDefinitionKey);
        }
    }

    private void checkInventory(DelegateExecution execution) throws Exception {
        String businessKey = execution.getBusinessKey();
        log.info("开始库存检查, businessKey: {}", businessKey);
        
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> orderItems = (List<Map<String, Object>>) 
            execution.getVariable("orderItems");
            
        // 模拟库存检查
        boolean hasShortage = false;
        for (Map<String, Object> item : orderItems) {
            String skuId = (String) item.get("skuId");
            Integer quantity = (Integer) item.get("quantity");
            
            // 模拟30%的概率出现缺货
            boolean itemHasStock = Math.random() > 0.3;
            if (!itemHasStock) {
                hasShortage = true;
                log.info("商品缺货: skuId={}, quantity={}", skuId, quantity);
            }
        }
        
        execution.setVariable("hasShortage", hasShortage);
        execution.setVariable("checkTime", System.currentTimeMillis());
        
        log.info("库存检查完成: hasShortage={}", hasShortage);
    }

    private void allocateLocation(DelegateExecution execution) throws Exception {
        String businessKey = execution.getBusinessKey();
        log.info("执行库位分配, businessKey: {}", businessKey);
        
        // 获取订单商品
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> items = (List<Map<String, Object>>) 
            execution.getVariable("orderItems");
            
        if (items == null) {
            items = new ArrayList<>();
            log.warn("未找到订单商品信息");
        }
        
        // 模拟库位分配
        for (Map<String, Object> item : items) {
            item.put("locationCode", "LOC-" + UUID.randomUUID().toString().substring(0, 8));
        }
        
        execution.setVariable("allocatedItems", items);
        log.info("库位分配完成, 分配商品数: {}", items.size());
    }

    private void generatePickTask(DelegateExecution execution) throws Exception {
        String businessKey = execution.getBusinessKey();
        log.info("生成拣货任务, businessKey: {}", businessKey);
        
        String pickTaskNo = "PICK_" + UUID.randomUUID().toString().substring(0, 8);
        execution.setVariable("pickTaskNo", pickTaskNo);
        execution.setVariable("pickTaskStatus", "CREATED");
        execution.setVariable("pickTaskCreateTime", System.currentTimeMillis());
        execution.setVariable("pickerId", "PICKER_001");
        
        log.info("拣货任务生成完成: pickTaskNo={}", pickTaskNo);
    }

    private void generateOutbound(DelegateExecution execution) throws Exception {
        String businessKey = execution.getBusinessKey();
        log.info("开始生成出库任务, businessKey: {}", businessKey);
        
        String outboundNo = "OUT_" + businessKey + "_" + System.currentTimeMillis();
        execution.setVariable("outboundNo", outboundNo);
        execution.setVariable("outboundTime", System.currentTimeMillis());
        
        log.info("出库任务生成完成, outboundNo: {}", outboundNo);
    }

    private void handlePurchaseInbound(DelegateExecution execution) throws Exception {
        String businessKey = execution.getBusinessKey();
        log.info("生成采购入库任务, businessKey: {}", businessKey);
        
        execution.setVariable("purchaseInboundTaskId", "PURCHASE_" + businessKey);
        execution.setVariable("purchaseInboundTime", System.currentTimeMillis());
        
        log.info("采购入库任务生成完成");
    }

    private void handleInboundSorting(DelegateExecution execution) throws Exception {
        String businessKey = execution.getBusinessKey();
        log.info("生成分拣任务, businessKey: {}", businessKey);
        
        execution.setVariable("sortingTaskId", "SORT_" + businessKey);
        execution.setVariable("sortingTime", System.currentTimeMillis());
        
        log.info("分拣任务生成完成");
    }

    private void handleHotDelivery(DelegateExecution execution) throws Exception {
        String businessKey = execution.getBusinessKey();
        log.info("生成热丰提货任务, businessKey: {}", businessKey);
        
        execution.setVariable("hotDeliveryTaskId", "HOT_" + businessKey);
        execution.setVariable("hotDeliveryTime", System.currentTimeMillis());
        
        log.info("热丰提货任务生成完成");
    }

    private void handleQualityCheck(DelegateExecution execution) throws Exception {
        String businessKey = execution.getBusinessKey();
        log.info("生成质检任务, businessKey: {}", businessKey);
        
        // 模拟生成质检任务
        execution.setVariable("qualityTaskId", "QUALITY_" + businessKey);
        execution.setVariable("qualityTime", System.currentTimeMillis());
        
        log.info("质检任务生成完成");
    }
} 